package longmethod;

import lombok.Getter;
import org.apache.commons.lang3.ArrayUtils;

@Getter
public class MethodTooLongR {

    public static final int DEFAULT_CAPACITY_ENLARGE_NUMBER = 10;
    private boolean readOnly;
    private int size;
    private Object[] elements;

    public MethodTooLongR(int length, boolean readOnly) {
        this.elements = new Object[length];
        this.readOnly = readOnly;
        this.size = 0;
    }

    public void add(Object element) {
        //守卫子句的写法，为方法显示的声明一个提前的出口
        if (readOnly) {
            return;
        }
        //将判断逻辑和具体执行的操作抽取成一个方法
        //提取魔法值
        if (isCapacityEnough()) {
            enlargeCapacity(DEFAULT_CAPACITY_ENLARGE_NUMBER);
        }
        //把最后添加元素的操作也抽取成方法，使它和方法中的其他部分在一个细节层面上
        addElement(element);
    }

    private void addElement(Object element) {
        elements[size++] = element;
    }

    private boolean isCapacityEnough() {
        return size + 1 > elements.length;
    }

    private void enlargeCapacity(int capacityEnlargeNumber) {
        Object[] newElements = new Object[this.elements.length + capacityEnlargeNumber];
        //引入数组操作类库简化代码
        ArrayUtils.addAll(newElements, this.elements);
        this.elements = newElements;
    }
}
